package com.yq.testmodule.tiktok

import android.app.Dialog
import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.RequiresApi
import androidx.compose.ui.graphics.Color
import com.fmt.mvi.learn.gobal.log
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetBehavior.BottomSheetCallback
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import com.yq.testmodule.R

class MyBottomSheetDialog : BottomSheetDialogFragment() {


    @RequiresApi(Build.VERSION_CODES.M)
    override fun onCreate(savedInstanceState: Bundle?) {
        requireActivity().window.decorView.setBackgroundColor(requireActivity().getColor(R.color.color_66000000))
        super.onCreate(savedInstanceState)
    }
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.activity_test_tiktok_bottom_sheet, container, false)
    }


    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        return BottomSheetDialog(requireContext(), R.style.myDialog)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        dialog.takeIf { it != null }.let { dialog as BottomSheetDialog }
            .also {

                it.dismissWithAnimation = true
                it.behavior.maxHeight = resources.displayMetrics.heightPixels * 1 / 2
                it.behavior.peekHeight = 0
                it.behavior.addBottomSheetCallback(object : BottomSheetCallback() {
                    override fun onStateChanged(bottomSheet: View, newState: Int) {
                    }

                    override fun onSlide(bottomSheet: View, slideOffset: Float) {
                        "slideOffset: $slideOffset".log()
                        if(slideOffset>=0){
                            mSlideCallBack?.invoke(slideOffset)
                        }
                    }

                })

                it.setOnShowListener { dialog ->
                    if (it.behavior.state == BottomSheetBehavior.STATE_COLLAPSED) {
                        it.behavior.state = BottomSheetBehavior.STATE_EXPANDED
                    }
                }
            }

    }

    private var mSlideCallBack: ((Float) -> Unit)? = null
    fun setSlideCallback(callback: (slideOffset: Float) -> Unit) {
        mSlideCallBack = callback
    }
}